import * as React from 'react';

import {IView} from '../types/IView';
import {IParentView} from '../types/IParentView';
import {IAttr} from '../types/IAttr';

import {IViewObject} from './IViewObject';
import AbsParentViewObject from './AbsParentViewObject';
import Sticky from '../components/Sticky';

export class DivViewObject extends AbsParentViewObject<IParentView> implements IViewObject<IParentView> {

  viewType = 'div';

  attrs: IAttr[] = [
    {
      name: 'id',
      display: 'ID',
      type: 'string',
      required: true,
      defaultValGenerator: () => {
        return `divView${this.viewIndex}`;
      }
    },
    {
      name: 'className',
      display: 'class',
      type: 'string',
      required: false,
      defaultValGenerator: () => {
        return '';
      }
    },
    {
      name: 'effect',
      display: '效果',
      type: 'select',
      required: false,
      defaultValGenerator: () => {
        return '';
      },
      values: [
        {
          name: 'stickOnTop',
          display: '滚动时停在页面顶部'
        }
      ]
    }
  ];

  create(designId: string): IParentView {
    return {
      id: this.generateId(),
      viewType: this.viewType,
      designId,
      style: {
        height: '50px'
      },
      attrVals: this.createAttrVals(this.attrs),
      children: []
    };
  }

  render(view: IParentView, refUpdater: (view: IView, ref: Element) => void): JSX.Element | null {
    const {attrVals} = view;

    const elemRefUpdater: React.Ref<Element> = el => refUpdater(view, el);
    const props: React.HTMLAttributes<HTMLElement> = {
      id: attrVals.id,
      className: attrVals.className,
      style: attrVals.className ? {} : view.style
    };

    if (attrVals.effect === 'stickOnTop') {
      return (
        <div>
          <Sticky designId={view.designId}>
            <div ref={elemRefUpdater} {...props}>
              {view.children.map(child => this.renderChild(child, refUpdater))}
            </div>
          </Sticky>
        </div>
      );

    } else {
      return (
        <div ref={elemRefUpdater} {...props}>
          {view.children.map(child => this.renderChild(child, refUpdater))}
        </div>
      );
    }
  }
}

const divViewObject = new DivViewObject();
export default divViewObject;
